<template>
  <div class="page">
    <AddressEdit
      :address-info="addressInfo"
      :tel-maxlength="11"
      :show-delete="showDelete"
      show-set-default
      :show-area="false"
      :is-deleting="deleteLoading"
      :is-saving="saveLoading"
      @save="onSave"
      @delete="onDelete"
    >
      <Cell title="称呼">
        <div style="display: flex; gap: 20px; justify-content: flex-end">
          <Button
            icon="circle"
            :plain="sex != 0"
            hairline
            type="primary"
            @click="sex = 0"
            size="mini"
            >先生</Button
          >
          <Button
            icon="circle"
            :plain="sex != 1"
            hairline
            type="success"
            @click="sex = 1"
            size="mini"
            >女士</Button
          >
        </div>
      </Cell>
    </AddressEdit>
  </div>
</template>
<script lang="ts" setup>
import {
  addAddress,
  getAddress,
  removeAddress,
  updateAddress,
} from "@/api/address";
import router from "@/router";
import { AddressEdit, Cell, Button } from "vant";
import { showToast } from "vant";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

/**显示删除按钮 */
const showDelete = ref(false);
const route = useRoute();
/**初始地址信息 */
const addressInfo = ref();
/**地址id */
const id = ref();
/**性别 */
const sex = ref(0);

const deleteLoading = ref(false);
const saveLoading = ref(false);
onMounted(() => {
  id.value = route.query.id;

  if (id.value) {
    getAddress(Number(id.value)).then((res) => {
      sex.value = res.data.sex;
      addressInfo.value = {
        tel: res.data.phoneNumber,
        name: res.data.userName,
        isDefault: res.data.isDefault,
        addressDetail: res.data.address,
      };
      showDelete.value = true;
    });
  }
});

const onSave = (info: any) => {
  saveLoading.value = true;
  const data = {
    address: info.addressDetail,
    userName: info.name,
    phoneNumber: info.tel,
    sex: sex.value,
    isDefault: info.isDefault,
  };
  if (id.value == null) {
    addAddress(data).then((res) => {
      showToast("保存成功");
      saveLoading.value = false;
      setTimeout(() => {
        router.back();
      }, 1000);
    });
  } else {
    data["id"] = id.value;
    updateAddress(data).then((res) => {
      showToast("保存成功");
      saveLoading.value = false;
      setTimeout(() => {
        router.back();
      }, 1000);
    });
  }
};
const onDelete = () => {
  deleteLoading.value = true;
  removeAddress(id.value).then((res) => {
    showToast("删除成功");
    deleteLoading.value = false;
    setTimeout(() => {
      router.back();
    }, 1000);
  });
};
</script>
<style lang="less" scoped></style>
